<template>
  <!-- 弹出的卡片 -->
  <div class="knownCard--box">
    <!-- 顶部----------- -->
    <div class="kc-top">
      <!-- 按钮组 -->
      <div class="iconGroup">
        <el-tooltip
          class="item"
          effect="dark"
          content="编辑"
          placement="top"
          popper-class="knowntooltip"
          v-if="cardData.createBy == this.$store.state.user.userId"
        >
          <!-- <svg-icon icon-class="knEdit" @click="addTaskDrawer = true" /> -->
          <svg-icon icon-class="knEdit" @click="editClick" />
        </el-tooltip>
        <el-tooltip
          class="item"
          effect="dark"
          content="分享"
          placement="top"
          popper-class="knowntooltip"
        >
          <svg-icon icon-class="knShare" />
        </el-tooltip>
        <el-tooltip
          class="item"
          effect="dark"
          content="删除"
          placement="top"
          popper-class="knowntooltip"
          v-if="cardData.createBy == this.$store.state.user.userId"
        >
          <svg-icon icon-class="knDelete" @click="removeBtn" />
        </el-tooltip>
        <i class="el-icon-close" @click="$emit('closeCard')"></i>
      </div>
      <!-- 内容 -->
      <h3>{{ cardObj.name }}</h3>
      <p>
        <span>{{ getTimeTxt() }}</span>
        <el-tooltip
          class="item"
          effect="dark"
          :content="getRepeatDays()"
          placement="top-start"
          popper-class="repeatTool"
        >
          <span class="week-s">{{ getRepeatDays() }}</span>
        </el-tooltip>
      </p>
      <!-- 功能区 -->
      <div class="kc-fun">
        <svg-icon icon-class="chat" />
        <svg-icon icon-class="voice" />
        <svg-icon icon-class="video" />
      </div>
    </div>

    <!-- 底部----------- -->
    <!-- 任务其他信息 -->
    <div class="taskInfo">
      <!-- 创建人 -->
      <div class="taskInfo_item">
        <div class="flex flex_ac">
          <svg-icon icon-class="person_icon" />
          <img class="avatar" :src="cardObj.createAvatar || defaultAvatar" />
          <span class="name font_28">{{ cardObj.createName }}</span>
        </div>
      </div>
      <!-- 参与者 -->
      <div class="taskInfo_item">
        <div class="flex flex_ac">
          <svg-icon icon-class="persons_icon" />
          <span class="name font_28" v-if="cardObj.id"
            >{{ cardObj.userList.length }}位参与者</span
          >
          <!-- <div class="font_28 color_999" v-if="getTakeNum()">
            · {{ getTakeNum() }}人接受
          </div> -->
        </div>
        <template v-if="cardObj.id && cardObj.userList.length > 0">
          <div
            class="participator flex flex_ac"
            :class="indexs == 0 ? 'm_t_17' : ''"
            v-for="(items, indexs) in cardObj.userList"
            :key="indexs"
          >
            <div class="parC-img">
              <img class="avatar" :src="items.avatar || defaultAvatar" />
              <!-- <svg-icon icon-class="check_on" v-if="items.status == '0'" /> -->
            </div>
            <span class="name font_28">{{ items.name }}</span>
          </div>
        </template>
      </div>
      <!-- 提前几分钟提醒 -->
      <div class="taskInfo_item">
        <div class="flex flex_ac">
          <svg-icon icon-class="hint_icon" />
          <span class="name font_28">{{ getHintTxt() }}</span>
        </div>
      </div>
      <!-- 类型 -->
      <div class="taskInfo_item">
        <div class="flex flex_ac">
          <svg-icon icon-class="code_icon" />
          <span class="name font_28">{{ cardObj.targetName }}</span>
        </div>
      </div>
    </div>
    <!-- 任务其他信息 -->

    <!-- 底部按钮 -->
    <div class="kc-b" v-if="cardObj.createBy == $store.state.user.userId">
      <!-- 切换状态 -->
      <p :class="statusTxt == '未标记' ? 'isRed' : ''">
        {{ statusTxt }} <i class="el-icon-arrow-down"></i>
      </p>
      <el-select
        v-model="cardObj.status"
        placeholder="请选择"
        @change="changeStatus"
      >
        <el-option
          v-for="item in statusList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
    </div>
    <div class="kc-btn" v-else>
      <!-- 接受拒绝按钮 -->
      <el-button
        @click="editStatus(0)"
        :class="getTakeTxt() ? 'isActive' : ''"
        :disabled="getTakeTxt() || getRefuseTxt()"
        >{{ getTakeTxt() ? "已接受" : "接受" }}</el-button
      >
      <el-button
        @click="editStatus(1)"
        :class="getRefuseTxt() ? 'isRefuse' : ''"
        :disabled="getTakeTxt() || getRefuseTxt()"
        >{{ getRefuseTxt() ? "已拒绝" : "拒绝" }}</el-button
      >
    </div>

    <!-- 弹出的编辑任务框 -->
    <el-drawer
      :title="cardObj.id ? '编辑任务' : '创建任务'"
      size="40%"
      :visible.sync="addTaskDrawer"
      @close="addTaskClose"
      popper-class="cardEdit"
      :modal-append-to-body="false"
    >
      <AddTask
        ref="addTask"
        :selectObj="cardData"
        :editObj="cardObj"
        @reqOrClose="reqOrClose"
      ></AddTask>
    </el-drawer>
  </div>
</template>

<script>
import AddTask from "@/BMViews/views/knownAction/table/addTask.vue";
import {
  getInfoServiceActionTaskApi,
  removeServiceActionTaskApi,
  updateStatusActionTaskApi,
  updateTodayStatusApi,
  updateTaskUserStatusActionTaskApi
} from "@/BMViews/api/service/actionTask.js";

import { timestampToTime, TurnChinese,transferTime } from "@/wss/utils/wss.js";
export default {
  name: "knownCard",
  components: {
    AddTask
  },
  props: {
    // 当前卡片的数据
    cardData: {
      type: Object,
      default: () => {
        return {};
      }
    },
    dateValue:{
      type:String,
      default:''
    }
  },
  data() {
    return {
      addTaskDrawer: false, //是否显示编辑框

      cardObj: {}, //当前任务的详细信息
      defaultAvatar: require("@/assets/images/defaultAvatar.jpg"), //默认头像
      // 人员
      personData: [],
      statusTxt: "", //选择框的文本
      // 选择框
      statusList: [
        {
          value: "-1",
          label: "取消"
        },
        {
          value: "1",
          label: "未完成"
        },
        {
          value: "2",
          label: "完成"
        }
      ],
      statusValue: 0 //选择的值
    };
  },
  mounted() {},
  watch: {
    cardObj: {
      deep: true,
      handler() {
        this.getStatusTxt(); // 获取状态的名字
      }
    }
  },
  methods: {
    //    点击了编辑按钮
    editClick() {
      this.addTaskDrawer = true;
    },

    // 编辑框关闭的时候
    addTaskClose() {},

    // 刷新列表并且关闭弹出框
    reqOrClose() {
      this.addTaskDrawer = false; //关闭弹出框
    },

    // 获取当前点击的这个任务的详细数据
    async getInfoServiceActionTask() {
      let id = this.cardData.id;
      let result = await getInfoServiceActionTaskApi({ id });
      if (result.code == 200) {
        this.cardObj = result.data;
        //完成数据之后重新计算位置
        this.$nextTick(() => {
          this.$emit("againPlace"); //重新计算位置
        });
      }
    },

    // 获取时间
    getTimeTxt() {
      let row = this.cardObj; //当前卡片的数据
      // 获取今天的日期
      let date = new Date();
      let day = timestampToTime(date);
      let dayArr = day.split("-");
      return `${dayArr[1].trim()}月${dayArr[2].trim()}日(今天) ${
        row.startTime
      }~${row.endTime}`;
    },

    // 获取怎样的重复
    getRepeatDays() {
      if (!this.cardObj.id) return;
      let row = this.cardObj; //当前卡片的数据
      if (row.repeatDays.includes("；")) {
        // 是每周重复
        let arr = row.repeatDays.split("；");
        let str = [];
        // TurnChinese
        arr.forEach(item => {
          str.push(`星期${TurnChinese(item)}`);
        });
        return str.join(",");
      } else {
        // 不是每周重复
        const stateMap = {
          "-1": "不重复",
          0: "工作日重复",
          9: "每天重复"
        };
        return stateMap[row.repeatDays];
      }
    },

    // 获取提前几分钟
    getHintTxt() {
      let row = this.cardObj; //当前卡片的数据
      if (row.notice == "0") {
        return "不提醒";
      } else {
        return `提前${row.notice}分钟`;
      }
    },

    // 获取任务目标的名字
    getTargetName() {
      let row = this.cardObj; //当前卡片的数据
      if (row.targetType) {
        const stateMap = {
          1: "事业",
          2: "亲友",
          3: "健康"
        };
        let type = stateMap[row.targetType];
        return `${type}`;
      } else {
        return "";
      }
    },

    // 获取接受的人数
    getTakeNum() {
      if (!this.cardObj.id) return;
      let num = 0;
      this.cardObj.userList.forEach(item => {
        if (item.status == "0") {
          num = num + 1;
        }
      });
      return num;
    },

    // 点击删除按钮
    removeBtn() {
      this.$confirm("是否删除该任务?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "cardMess"
      })
        .then(() => {
          this.removeServiceActionTask(); // 删除的接口
        })
        .catch(() => {});
    },

    // 删除的接口
    async removeServiceActionTask() {
      let id = this.cardObj.id;
      let result = await removeServiceActionTaskApi({ id });
      if (result.code == 200) {
        this.$emit("refreshList");
        this.$message({ message: "删除成功", type: "success" });
      }
    },

    // 获取状态的名字
    getStatusTxt() {
      console.log("获取状态的名字获取状态的名字");
      let row = this.cardObj;
      if (row.status) {
        // 有状态数据
        const stateMap = {
          "-1": "取消",
          1: "未完成",
          2: "完成"
        };
        this.statusTxt = stateMap[row.status];
      } else {
        // 开始时间还没到就是未到期，开始时间到了就是未标记(红色的字)
        let start = timestampToTime(row.startDay) + row.startTime + ":00";
        let startDate = new Date(start).getTime();
        let nowDate = new Date().getTime();
        // console.log(startDate,nowDate,'获取状态的名字获取状态的名字');
        // 开始时间大于当前时间
        if (startDate > nowDate) {
          this.statusTxt = "未到期";
        } else {
          this.statusTxt = "未标记";
        }
      }
    },

    // 修改状态
  async  changeStatus() {
    
     console.log(this.cardObj,'数据');
      if(this.cardObj.repeatDays == -1){
          // 不重复修改状态
        await	this.updateStatusActionTask(); // 修改任务状态
					await this.updateTodayStatusFn() // 修改当天任务状态
      }else{
        	// 重复的
					if (this.cardObj.status == -1) {//取消状态
					 await  this.updateStatusActionTask(); // 编辑一个任务的接口
					await this.updateTodayStatusFn() // 修改当天任务状态
					} else {
					await	this.updateTodayStatusFn() // 修改当天任务状态
					}
      }
      this.$emit("refreshList"); // 重新查询任务列表
        this.$message({ message: "编辑成功", type: "success" });
      
    },

    // 修改任务状态的接口
    async updateStatusActionTask() {
      let cardObj = this.cardObj;
      let result = await updateStatusActionTaskApi([cardObj]);
    },
    // 修改当天的任务状态接口
    async updateTodayStatusFn(){
        let cardObj = this.cardObj;
				// --------------------传递修改状态参数的接口--------------------
				let date = new Date()
				let data = {
					status:cardObj.status, //状态值
					// todayStatus: this.statusList[e.detail.value].value, //状态值
					targetId: cardObj.targetId, //目标id
					taskId: cardObj.id, //任务id
					taskDate: this.dateValue, //编辑的任务时间 没有传就用当天时间
				}
        console.log(data,'传入数据');
        let res = await updateTodayStatusApi([data])
    },

    // 点击接受拒绝按钮
    editStatus(status) {
      this.updateTaskUserStatusActionTask(status);
    },

    // 修改任务的状态接口
    async updateTaskUserStatusActionTask(status) {
      let data = {
        taskId: this.cardObj.id,
        status: status
      };
      let result = await updateTaskUserStatusActionTaskApi(data);
      if (result.code == 200) {
        this.getInfoServiceActionTask(); // 获取当前点击的这个任务的详细数据
        this.$emit("refreshList"); // 重新查询任务列表
        this.$message({ message: "操作成功", type: "success" });
      }
    },

    // 获取接受的状态
    getTakeTxt() {
      if (!this.cardObj.id) return;
      let user = this.cardObj.userList.find(item => {
        return item.userId == this.$store.state.user.userId;
      });
      // 判断接受的
      if (user) {
        if (user.status == "0") {
          return true;
        } else {
          return false;
        }
      }
    },

    // 获取拒绝的状态
    getRefuseTxt() {
      if (!this.cardObj.id) return;
      let user = this.cardObj.userList.find(item => {
        return item.userId == this.$store.state.user.userId;
      });
      // 判断拒绝的
      if (user) {
        if (user.status == "1") {
          return true;
        } else {
          return false;
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.knownCard--box {
  box-sizing: border-box;
}
// 顶部-----------
.kc-top {
  padding: 15px 20px;
  background-color: #f7f7f7;
  h3 {
    font-size: 16px;
    font-weight: 400;
    color: #666;
    margin-top: 10px;
    margin-bottom: 5px;
  }
  p {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    font-size: 13px;
    color: #666;
    .week-s {
      width: 90px;
      text-align: right;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      -o-text-overflow: ellipsis;
    }
  }
  .kc-fun {
    display: flex;
    justify-content: space-around;
    border-top: 1px solid #efefef;
    padding-top: 15px;
    margin-top: 15px;
    svg {
      font-size: 20px;
      cursor: pointer;
    }
  }
}
// 按钮组
.iconGroup {
  display: flex;
  justify-content: flex-end;
  i {
    margin-left: 12px;
    font-size: 18px;
    cursor: pointer;
  }
  svg {
    margin-left: 15px;
    font-size: 16px;
    cursor: pointer;
  }
}

// 下半部分任务其他信息
.taskInfo {
  padding: 16px 20px 0;

  .taskInfo_item {
    margin-bottom: 24px;
    svg {
      margin-right: 15px;
    }
  }

  .icon {
    width: 14px;
    height: 14px;
    margin-right: 11px;
  }

  .avatar {
    width: 25px;
    height: 25px;
    border-radius: 50%;
    margin-right: 5px;
  }

  .name {
    color: #333333;
    margin-right: 5px;
  }

  .mark {
    height: 16px;
    color: #333333;
    border-radius: 2px;
    text-align: center;
    line-height: 16px;
  }

  .participator {
    margin: 0 0 10px 26px;
    .parC-img {
      display: flex;
      position: relative;
      svg {
        position: absolute;
        right: 2px;
        bottom: -2px;
        margin: 0;
        font-size: 12px;
      }
    }
  }
  .m_t_17 {
    margin-top: 17px;
  }
}

// 底部
.kc-b {
  position: relative;
  border: 1px solid #ddd;
  border-radius: 5px;
  margin: 0 20px;
  margin-bottom: 10px;
  padding: 10px 0;
  p {
    text-align: center;
  }
  .isRed {
    color: #ff0000;
  }
  .el-select {
    position: absolute;
    top: 0;
    opacity: 0;
    width: 100%;
    display: block;
    margin: 0 auto;
    ::v-deep .el-input__inner {
      text-align: center;
    }
    ::v-deep .el-input__suffix {
      right: 100px;
    }
  }
}
// 接受拒绝按钮
.kc-btn {
  display: flex;
  margin: 0 20px;
  margin-bottom: 10px;
  .el-button {
    flex: 1;
    &:hover {
      color: #606266;
      border-color: #dcdfe6;
      background-color: #fff;
    }
    &:focus {
      color: #606266;
      border-color: #dcdfe6;
      background-color: #fff;
    }
  }
  // 接受
  .isActive {
    color: #207a1c;
    border-color: #207a1c;
    background-color: #effbee;
    &:hover {
      color: #207a1c;
      border-color: #207a1c;
      background-color: #effbee;
    }
  }
  // 拒绝
  .isRefuse {
    color: #f87a23;
    border-color: #f87a23;
    background-color: #fff;
    &:hover {
      color: #f87a23;
      border-color: #f87a23;
      background-color: #fff;
    }
  }
}

/* 抽屉样式 */
::v-deep .el-drawer__header {
  border-bottom: 1px solid #efefef;
  padding-bottom: 15px;
  margin-bottom: 20px;
}
::v-deep .el-drawer__header > span {
  font-size: 18px;
  font-weight: 400;
  color: #2e3f5e;
  padding-left: 20px;
  background: url("~@/wss/assets/image/icon/cardLeft.png") left center no-repeat;
  background-size: 7px;
}
</style>
<style>
.repeatTool {
  z-index: 10001 !important;
}
.cardEdit {
  /* z-index: 10001!important; */
}
.knowntooltip {
  z-index: 10000 !important;
}
</style>
